import Vue from 'vue'
import store from '@/store'
import router, { resetRouter } from '@/router'
import { userLogin, userLogout, choicePositionLogin } from '@/api/auth'
import { avoidCloseLogin } from '@/api/role'
import { ACCESS_TOKEN, LOGIN_DEPT_POSITION, NAME, STORE } from '@/store/mutation-types'
import { welcome, removeSession, setSession, getSession } from '@/utils/util'
import { noticeCount } from '@/api/notify'

const user = {
  state: {
    token: '',
    name: '',
    welcome: '',
    avatar: '',
    roles: [],
    info: {},
    permissions: [],
    menus: [],
    addRouters: [],
    notifyCount: 0
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      Vue.ls.set('token', token)
      state.token = token
    },
    SET_NAME: (state, { name, welcome }) => {
      state.name = name
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
      Vue.ls.set('userInfo', info)
    },
    SET_NOTIFYCOUNT: (state, count) => {
      state.notifyCount = count
    }
  },

  actions: {
    // 登录
    Login({ commit, dispatch }, userInfo) {
      return new Promise(async (resolve, reject) => {
        userLogin(userInfo)
          .then(async response => {
            const result = response.data
            // 权限数组赋值到角色里面去
            result.user.permissions = result.permissions
            result.user.menus = result.menus
            result.user.signature = result.userAutographVO // 签名，用于工作流审核时显示签名图片
            dispatch('setLoginUser', response).then(() => {
              resolve(response)
            }).catch((err) => {
              reject(err)
            })

          }).catch(err => {
            reject(err)
          })
      })
    },

    // 获取用户信息
    GetInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getInfo().then(response => {
          const result = response.result

          if (result.role && result.role.permissions.length > 0) {
            const role = result.role
            role.permissions = result.role.permissions
            role.permissions.map(per => {
              if (per.actionEntitySet != null && per.actionEntitySet.length > 0) {
                const action = per.actionEntitySet.map(action => { return action.action })
                per.actionList = action
              }
            })
            role.permissionList = role.permissions.map(permission => { return permission.permissionId })
            commit('SET_ROLES', result.roles)
            commit('SET_INFO', result)
          } else {
            reject(new Error('getInfo: roles must be a non-null array !'))
          }

          // commit('SET_NAME', { name: result.name, welcome: welcome() })
          // commit('SET_AVATAR', result.avatar)

          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    getLocalUserInfo({ commit, dispatch }) {
      return new Promise((resolve, reject) => {
        const token = Vue.ls.get(ACCESS_TOKEN) || ''
        const urlArr = Vue.ls.get('urlArr') || ''
        const userInfo = Vue.ls.get('userInfo')
        const response = {
          headers: {
            authorization: token
          },
          data: {
            sysParameters: urlArr,
            user: userInfo
          }
        }
        dispatch('setLoginUser', response).then(() => {
          resolve()
        }).catch((err) => {
          reject(err)
        })
      })
    },

    /**
     * 用户管理-成为该用户
     * @param {*} post 
     */
    changeUser({ commit, dispatch }, post) {
      return new Promise(async (resolve, reject) => {
        avoidCloseLogin(post).then(async response => {
          const result = response.data
          // 权限数组赋值到角色里面去
          result.user.permissions = result.permissions
          result.user.menus = result.menus
          result.user.signature = result.userAutographVO // 签名，用于工作流审核时显示签名图片
          dispatch('setLoginUser', response).then(() => {
            resolve(response)
          }).catch((err) => {
            reject(err)
          })
        }).catch((err) => {
          reject(err)
        })
      })
    },

    /**
     * 登录成功/成为该用户成功/切换岗位成功 时统一使用这个方法设置当前登录用户的信息
     * @param response 登录成功/成为该用户成功/切换岗位成功返回的数据
     */
    setLoginUser({ commit }, response) {
      return new Promise(async (resolve, reject) => {
        try {
          const token = (response.headers && response.headers.authorization) || ''
          const result = response.data
          Vue.ls.set(ACCESS_TOKEN, token, 12 * 60 * 60 * 1000)
          commit('SET_TOKEN', token)
          commit('SET_INFO', result.user)
          Vue.ls.set('urlArr', result.sysParameters)
          // Vue.ls.set('userInfo', result.user)
          commit('SET_ROLES', result.roles)
          commit('SET_NAME', {
            name: (result.user && result.user.name) || '',
            welcome: welcome()
          })
          // generate accessible routes map based on roles
          const accessRoutes = await store.dispatch('GenerateRoutes')
  
          // dynamically add accessible routes
          router.addRoutes(accessRoutes)
          resolve()
        } catch(e) {
          reject(e)
        }
      })
    },

    // 登出
    Logout({ commit, dispatch }, empty) {
      return new Promise((resolve) => {
        if (empty) {
          dispatch('clearLoginInfo').then(() => {
            resolve()
          }).catch((err) => {
            reject(err)
          })
        } else {
          userLogout().then(() => {
            resolve()
          }).catch(() => {
            resolve()
          }).finally(() => {
            dispatch('clearLoginInfo').then(() => {
              resolve()
            }).catch((err) => {
              reject(err)
            })
          })
        }
      })
    },
    clearLoginInfo({ commit }) {
      return new Promise(async (resolve, reject) => {
        try {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          Vue.ls.remove(ACCESS_TOKEN)
          Vue.ls.remove('userInfo')
          Vue.ls.remove('Store-State')
          // removeSession('userInfo')
          // removeSession('STORE')
          removeSession('haveSeeNotice')
          resetRouter()
          //Vue.ls.remove(STORE)
          resolve()
        } catch(e) {
          reject(e)
        }
      })
    },

    /**
     * 
     * @param {*} param
     * @param {*} position 
     */
    // dynamically modify permissions
    changeLoginPosition({ commit, dispatch }, position) {
      return new Promise(async resolve => {
        resetRouter()
        // 根据position获取新的用户信息，并更新当前登录的用户信息 (参考login的处理)
        choicePositionLogin(position).then(async response => {
          const result = response.data
          // 权限数组赋值到角色里面去
          result.user.permissions = result.permissions
          result.user.menus = result.menus
          result.user.signature = result.userAutographVO // 签名，用于工作流审核时显示签名图片
          dispatch('setLoginUser', response).then(() => {
            resolve(response)
          }).catch((err) => {
            reject(err)
          })
        }).catch((err) => {
          reject(err)
        })

        // generate accessible routes map based on roles
        const accessRoutes = await store.dispatch('GenerateRoutes')

        // dynamically add accessible routes
        router.addRoutes(accessRoutes)

        // reset visited views and cached views
        // dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      })
    },

    // 获取页头右上角的消息通知数量
    getNotifyCount({ commit }, count) {
      return new Promise((resolve) => {
        if (count === 0) {
          commit('SET_NOTIFYCOUNT', 0)
        }
        noticeCount().then(res => {
          commit('SET_NOTIFYCOUNT', res.data)
          resolve()
        }).catch(() => {
          resolve()
        })
      })
    },
  }
}

export default user
